package org.sqp.oneplus;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.sqp.base.AbstractSignIn;
import org.sqp.base.PostBuilder;

import java.io.IOException;

public class BbsSign extends AbstractSignIn {
    private HttpClient client = null;
    private String formHash = null;

    @Override
    public String title() {
        return "一加论坛签到：";
    }

    @Override
    public void login() {
        client = getNewClient();
        String token = get("oneplus.t");

        HttpGet get1 = new HttpGet("http://www.oneplusbbs.com/api/mobile/index.php?version=5&module=profile");
        get1.addHeader("Cookie",token);
        get1.addHeader("Cookie2","$Version=1");

        try {
            HttpResponse response = client.execute(get1);
            this.formHash = JSON.parseObject(EntityUtils.toString(response.getEntity())).getJSONObject("Variables").getString("formhash");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //http://account.oneplus.cn/login/login?rem=0
    //http://www.oneplusbbs.com/setssocookie.php?SSOKEY=ONEPLUSID&SSOVAL=&REM=0
    @Override
    public void sign() {
        if (formHash==null || "".equals(formHash)){
            System.out.println("获取formhash失败,已签到过或登陆失效。");
        }else{
            System.out.println("正在使用formHash："+formHash+" 进行签到...");
            HttpPost post = new PostBuilder("http://www.oneplusbbs.com/plugin.php?id=dsu_paulsign:sign&operation=qiandao&infloat=1&inajax=1")
                    .addParam("formhash",formHash)
                    .addParam("qdxq","kx")
                    .addParam("qdmode","1")
                    .addParam("todaysay","开心快乐每一天")
                    .build();
            try {
                String html = EntityUtils.toString(client.execute(post).getEntity());
                System.out.println(html);
                for (Element e:Jsoup.parse(html).select("#messagetext p:nth-child(1)")){
                    System.out.println(e.text());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
